import axios, { AxiosError } from "axios"
import store from "@/store"
import { Toast } from "antd-mobile"
import { customHistory } from "./history"
import { setToken, clearToken } from "./auth"

const http = axios.create({
  timeout: 5000, 
  baseURL: "http://toutiao.itheima.net/v1_0",
})

http.interceptors.request.use(
  (config) => {
    let {  login: { token } } = store.getState() 
    if (!config.url?.startsWith("/authorizations")) {
      config.headers!["Authorization"] = `Bearer ${token}` 
    }
    return config
  },
  (error) => Promise.reject(error)
)

http.interceptors.response.use((response) => {
    return response.data ? response.data : {}
  },
  async (error: AxiosError) => {
    if (error.response?.status === 401) {
      try {
        let {
          login: { refresh_token },
        } = store.getState() 
        if (!refresh_token) {
          await Promise.reject(error) 
        }
        const {
          data: {
            data: { token },
          },
        } = await axios({
          url: "http://toutiao.itheima.net/v1_0/authorizations",
          method: "put",
          headers: {
            Authorization: `Bearer ${refresh_token}`,
          },
        })
        const TokenObj = {
          token, 
          refresh_token, 
        }
        setToken(TokenObj)
        store.dispatch({ type: "login/token", payload: TokenObj }) 
        return http(error.config) 
      } catch (error) {
        clearToken() 
        store.dispatch({ type: "login/logout" }) 
        Toast.show({
          content: "登录超时, 请重新登录",
          duration: 1000,
          afterClose: () => {
            customHistory.push("/login", {
              from: customHistory.location.pathname, 
            })
          },
        })
      }
    }
    return Promise.reject(error)
  }
)

export { http }
